package com.couldsail.takeaway.controller.general;

import com.couldsail.takeaway.common.result.Result;
import com.couldsail.takeaway.utils.LocationUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadController {
    private final String directory = "E:";
    private final String imageUrl = "";//域名
    @PostMapping("/uploads")
    public Result<String> uploadFiles(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传失败，文件为空");
        }
        // 使用UUID生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFileName = UUID.randomUUID() + fileExtension;
        String upload = upload(file, newFileName);

        return Result.success(upload);

    }
    public String upload(MultipartFile file, String name) throws IOException {
        // 检查并创建上传目录
        File dir = new File(directory);
        if (!dir.exists()) {
            // 目录不存在则创建目录
            dir.mkdirs();
        }

        // 将文件保存到指定位置
        File dest = new File(directory + name);
        // 移动目录
        file.transferTo(dest);

        return imageUrl + name;
    }
}
